<template>
    <!-- 弹出层容器 -->
    <div class="login-modal">
        <!-- 关闭按钮 -->
        <button @click="closeLogin" class="close-btn">
            <i class="fa fa-times"></i>
        </button>

        <div class="flex w-full max-w-6xl bg-white rounded-2xl shadow-xl overflow-hidden login-container">
            <!-- 左侧内容 (PC端显示) -->
            <div class="ennea-sidebar w-1/2 ennea-bg text-white p-12 flex flex-col justify-between">
                <div>
                    <div class="enneagram-icon mb-8">
                        <i class="fa fa-user-circle fa-5x text-4xl text-purple-600"></i>
                    </div>
                    <h1 class="text-4xl font-bold mb-4">九型人格系统</h1>
                    <p class="text-xl opacity-90 mb-6">探索你的性格类型，发现真实的自我</p>
                    <ul class="space-y-3">
                        <li class="flex items-center">
                            <i class="fa fa-check-circle mr-2 text-green-300"></i>
                            <span>专业的人格类型评估</span>
                        </li>
                        <li class="flex items-center">
                            <i class="fa fa-check-circle mr-2 text-green-300"></i>
                            <span>详细的性格分析报告</span>
                        </li>
                        <li class="flex items-center">
                            <i class="fa fa-check-circle mr-2 text-green-300"></i>
                            <span>个性化成长建议</span>
                        </li>
                    </ul>
                </div>
                <div class="text-sm opacity-80">
                    <p>
                        还没有账号？<a href="#" @click.prevent="goToRegister" class="text-purple-300 font-medium hover:text-purple-100">立即注册</a>
                        开始你的性格探索之旅
                    </p>
                    <!-- <button @click="goToRegister" class="mt-4 px-6 py-2 bg-white text-purple-600 rounded-full font-medium hover:bg-opacity-90 transition">
                        注册账号
                    </button> -->
                </div>
            </div>

            <!-- 右侧登录表单 -->
            <div class="w-full md:w-1/2 p-8 md:p-12">
                <div class="flex justify-center items-center mb-8">
                    <!-- <img src="~assets/image/jiuxin_logo.jpg" class="w-20" /> -->
                    <i class="fa fa-user-circle fa-4x text-3xl text-purple-600"></i>
                    <!-- <h2 class="text-2xl font-bold text-gray-800">九型人格系统</h2> -->
                </div>
                <!-- <div class="flex justify-center items-center mb-8">
                    <h2 class="text-3xl font-bold text-gray-800 mb-2">欢迎登陆</h2>
                </div> -->

                <!-- 登录表单 -->
                <form @submit.prevent="handleLogin" class="space-y-6">
                    <div>
                        <label for="username" class="block text-sm font-medium text-gray-700 mb-1">用户名/邮箱/手机号</label>
                        <input
                            type="text"
                            id="username"
                            v-model="loginForm.username"
                            @blur="validateUsername"
                            class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500 transition"
                            :class="{ 'border-red-500': formErrors.username }"
                            placeholder="请输入用户名、邮箱或手机号"
                        />
                        <p v-if="formErrors.username" class="mt-1 text-sm text-red-600">{{ formErrors.username }}</p>
                    </div>

                    <div>
                        <label for="password" class="block text-sm font-medium text-gray-700 mb-1">密码</label>
                        <input
                            type="password"
                            id="password"
                            v-model="loginForm.password"
                            @blur="validatePassword"
                            class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500 transition"
                            :class="{ 'border-red-500': formErrors.password }"
                            placeholder="请输入密码"
                        />
                        <p v-if="formErrors.password" class="mt-1 text-sm text-red-600">{{ formErrors.password }}</p>
                        <div class="flex justify-between mt-2">
                            <div class="flex items-center">
                                <input
                                    type="checkbox"
                                    id="keep"
                                    v-model="loginForm.keep"
                                    class="h-4 w-4 text-purple-600 focus:ring-purple-500 border-gray-300 rounded"
                                />
                                <label for="keep" class="ml-2 block text-sm text-gray-700">记住我</label>
                            </div>
                            <a href="#" @click.prevent="forgotPassword" class="text-sm text-purple-600 hover:text-purple-800">忘记密码?</a>
                        </div>
                    </div>

                    <div>
                        <label for="captcha" class="block text-sm font-medium text-gray-700 mb-1">验证码</label>
                        <div class="captcha-container">
                            <input
                                type="text"
                                id="captcha"
                                v-model="loginForm.captcha"
                                @blur="validateCaptcha"
                                class="flex-1 px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500 transition"
                                :class="{ 'border-red-500': formErrors.captcha }"
                                placeholder="请输入验证码"
                            />
                            <div
                                class="captcha-image w-32 h-12 bg-gray-200 rounded-lg flex items-center justify-center text-gray-500 text-sm"
                                @click="onChangeCaptcha"
                            >
                                <img class="w-full h-full object-cover" :src="buildCaptchaUrl() + '&id=' + loginForm.captchaId" />
                            </div>
                        </div>
                    </div>

                    <button
                        type="submit"
                        class="w-full bg-purple-600 text-white py-3 px-4 rounded-lg font-medium hover:bg-purple-700 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:ring-offset-2 transition"
                    >
                        登录
                    </button>
                </form>

                <!-- 社交登录 -->
                <div class="mt-8">
                    <div class="relative">
                        <div class="absolute inset-0 flex items-center">
                            <div class="w-full border-t border-gray-300"></div>
                        </div>
                        <div class="relative flex justify-center text-sm">
                            <span class="px-2 bg-white text-gray-500">其他登录方式</span>
                        </div>
                    </div>

                    <div class="grid gap-4 mt-6">
                        <button @click="openSocialLogin('wechat')" class="social-login-btn wechat-btn text-white py-2 rounded-lg flex items-center justify-center">
                            <i class="fa fa-weixin text-xl mr-2"></i>
                            <span>微信</span>
                        </button>
                        <!-- <button
                            @click="openSocialLogin('alipay')"
                            class="social-login-btn alipay-btn text-white py-2 rounded-lg flex items-center justify-center"
                        >
                            <i class="fa fa-alipay text-xl mr-2"></i>
                            <span>支付宝</span>
                        </button>
                        <button
                            @click="openSocialLogin('weibo')"
                            class="social-login-btn weibo-btn text-white py-2 rounded-lg flex items-center justify-center"
                        >
                            <i class="fa fa-weibo text-xl mr-2"></i>
                            <span>微博</span>
                        </button> -->
                    </div>
                </div>

                <!-- 社交登录弹窗 -->
                <WechatLogin
                    v-if="showSocialLogin"
                    :defaultTab="socialLoginType"
                    @close="showSocialLogin = false"
                    @success="handleSocialLoginSuccess"
                    @error="handleSocialLoginError"
                />

                <!-- 手机扫码登录 -->
                <!-- <div class="mt-8 p-4 border border-gray-200 rounded-lg">
                    <div class="flex items-center">
                        <div class="qrcode-container mr-4">
                            <div class="w-20 h-20 bg-gray-200 rounded flex items-center justify-center">
                                <i class="fa fa-qrcode text-3xl text-gray-400"></i>
                            </div>
                            <div class="qrcode-overlay">
                                <p class="text-sm text-gray-600 mb-2">扫码登录</p>
                                <i class="fa fa-mobile-alt text-xl text-purple-600"></i>
                            </div>
                        </div>
                        <div>
                            <h3 class="font-medium text-gray-800">手机扫码登录</h3>
                            <p class="text-sm text-gray-600">打开手机应用扫描二维码</p>
                        </div>
                    </div>
                </div> -->

                <!-- 注册链接 -->
                <div class="mt-8 text-center text-sm text-gray-600">
                    还没有账号？<a href="#" @click.prevent="goToRegister" class="text-purple-600 font-medium hover:text-purple-800">立即注册</a>
                </div>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, defineEmits, onMounted } from 'vue'
import { buildCaptchaUrl } from '/@/api/common'
import { uuid } from '/@/utils/random'
import { checkIn, retrievePassword } from '/@/api/frontend/user/index'
import { useUserInfo } from '/@/stores/userInfo'
import { useRouter } from 'vue-router'
import { useRoute } from 'vue-router'
import clickCaptcha from '/@/components/clickCaptcha'
import WechatLogin from './wechatLogin.vue'
import { ElMessage } from 'element-plus'
// 定义事件
const emit = defineEmits(['close'])
const route = useRoute()
const router = useRouter()
const userInfo = useUserInfo()

// 社交登录相关状态
const showSocialLogin = ref(false)
const socialLoginType = ref<'wechat' | 'alipay' | 'weibo'>('wechat')
// 登录表单数据
const loginForm = reactive({
    tab: 'login',
    username: '',
    password: '',
    keep: false,
    captcha: '',
    captchaId: uuid(),
    captchaInfo: '',
})
// 表单验证状态
const formErrors = reactive({
    username: '',
    password: '',
    captcha: '',
})

// 验证用户名
const validateUsername = () => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    const phoneRegex = /^1[3-9]\d{9}$/
    const usernameRegex = /^[a-zA-Z0-9_]{4,16}$/

    if (!loginForm.username) {
        formErrors.username = '请输入用户名/邮箱/手机号'
        return false
    }

    if (!emailRegex.test(loginForm.username) && !phoneRegex.test(loginForm.username) && !usernameRegex.test(loginForm.username)) {
        formErrors.username = '长度必须大于3位，只能是数字，字母，下划线和连字符'
        return false
    }

    formErrors.username = ''
    return true
}

// 验证密码
const validatePassword = () => {
    if (!loginForm.password) {
        formErrors.password = '请输入密码'
        return false
    }

    if (loginForm.password.length < 6) {
        formErrors.password = '密码长度至少为6位'
        return false
    }

    formErrors.password = ''
    return true
}

// 验证验证码
const validateCaptcha = () => {
    if (!loginForm.captcha) {
        formErrors.captcha = '请输入验证码'
        return false
    }
    formErrors.captcha = ''
    return true
}

const submitForm = () => {
    checkIn('post', loginForm).then((res) => {
        userInfo.dataFill(res.data.userInfo)
        if (route.query.to) return (location.href = route.query.to as string)
        router.push({ path: '/user/account/overview' })
    })
}
// 修改处理登录函数
const handleLogin = () => {
    const isUsernameValid = validateUsername()
    const isPasswordValid = validatePassword()
    const isCaptchaValid = validateCaptcha()
    if (!isUsernameValid || !isPasswordValid || !isCaptchaValid) {
        return
    }
    //如果有配置要验证码就先验证验证码
    if (userLoginCaptchaSwitch.value) {
        clickCaptcha(loginForm.captchaId, (captchaInfo) => {
            loginForm.captchaInfo = captchaInfo
            submitForm()
        })
    } else submitForm()
}

// 打开社交登录弹窗
const openSocialLogin = (type: 'wechat' | 'alipay' | 'weibo') => {
    socialLoginType.value = type
    showSocialLogin.value = true
}

// 处理社交登录成功
const handleSocialLoginSuccess = (result: any) => {
    showSocialLogin.value = false
    
    // 使用系统原有逻辑填充用户信息
    if (result && result.user_info) {
        userInfo.dataFill(result.user_info)
    }
    
    // 登录成功提示
    ElMessage.success('微信登录成功')
    
    // 处理跳转逻辑 - 优先使用to参数，其次使用redirect参数，最后默认跳转
    if (route.query.to) {
        location.href = route.query.to as string
    } else if (route.query.redirect) {
        router.push(route.query.redirect as string)
    } else {
        router.push('/index')
    }
}

// 处理社交登录错误
const handleSocialLoginError = (error: string) => {
    showSocialLogin.value = false
    ElMessage.error(error)
}

// 忘记密码
const forgotPassword = () => {
    alert('即将跳转到忘记密码页面 (模拟)')
}

// 跳转到注册
const goToRegister = () => {
    router.push({ name: 'register' })
}

// 添加关闭登录弹窗方法
const closeLogin = () => {
    emit('close')
}

const onChangeCaptcha = () => {
    loginForm.captcha = ''
    loginForm.captchaId = uuid()
}
const userLoginCaptchaSwitch = ref(false)
// 检查微信登录回调参数
const checkWechatCallback = () => {
    const urlParams = new URLSearchParams(window.location.search)
    const wechatLoginToken = urlParams.get('wechat_login_token')
    const error = urlParams.get('error')
    
    if (wechatLoginToken || error) {
        // 有微信登录相关参数，自动打开微信登录弹窗
        openSocialLogin('wechat')
    }
}
// 初始化时获取验证码
onMounted(() => {
    checkIn('get').then((res) => {
        userLoginCaptchaSwitch.value = res.data.userLoginCaptchaSwitch
    })
    
    // 检查是否有微信登录回调参数
    checkWechatCallback()
})


</script>

<style scoped>
body {
    font-family: 'Noto Sans SC', sans-serif;
    background-color: #f8f9fa;
}

/* 添加弹出层样式 */
.login-modal {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 1rem;
    z-index: 1000;
}

/* 添加关闭按钮样式 */
.close-btn {
    position: absolute;
    top: 20px;
    right: 20px;
    width: 40px;
    height: 40px;
    background-color: rgba(255, 255, 255, 0.2);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 20px;
    cursor: pointer;
    border: none;
    z-index: 1001;
    transition: all 0.3s ease;
}

.close-btn:hover {
    background-color: rgba(255, 255, 255, 0.3);
    transform: scale(1.1);
}

/* 修改登录容器样式 */
.login-container {
    max-height: 90vh;
    overflow-y: auto;
}

.ennea-bg {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.enneagram-icon {
    width: 80px;
    height: 80px;
    background: white;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow:
        0 10px 15px -3px rgba(0, 0, 0, 0.1),
        0 4px 6px -2px rgba(0, 0, 0, 0.05);
}

.captcha-container {
    display: flex;
    gap: 10px;
}

.captcha-image {
    border: 1px solid #e2e8f0;
    border-radius: 4px;
    cursor: pointer;
}

.alipay-icon svg {
    display: inline-block;
    vertical-align: middle;
    width: 1.2em;
    height: 1.2em;
}

.social-login-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0.5rem 0.75rem;
}

.social-login-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
}

.wechat-btn {
    background-color: #07c160;
}

.alipay-btn {
    background-color: #1677ff;
}

.weibo-btn {
    background-color: #e6162d;
}

.qrcode-container {
    position: relative;
}

.qrcode-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 0.9);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.3s ease;
    pointer-events: none;
}

.qrcode-container:hover .qrcode-overlay {
    opacity: 1;
    pointer-events: auto;
}

@media (max-width: 768px) {
    .ennea-sidebar {
        display: none;
    }

    .login-container {
        width: 100% !important;
        max-width: 450px !important;
        border-radius: 1rem !important;
    }
}

@media (max-width: 480px) {
    .login-container {
        max-width: 100% !important;
        margin: 0 1rem;
    }

    .close-btn {
        top: 10px;
        right: 10px;
    }
}
</style>
